package applog

import (
	"gitee.com/ymofen/gobase"
	"github.com/spf13/cobra"
	"kpl-plugs/plugs/appslog"
	"os"
)

func init() {
	gobase.ArgFuncRegister("corba.applogs", gobase.ArgFuncOption{Catalog: "corbaRoot", Func: func(args string, tag interface{}) (val interface{}, err error) {
		var logfile string = os.Getenv("applog_filename")
		var logflag bool = gobase.TryStrToBool(os.Getenv("applog_enable"), false)
		var loglevel string = os.Getenv("applog_level")
		if logflag {
			if len(logfile) == 0 {
				logfile = "log/app.log"
				loglevel = "INFO"
			}
		}

		var applogfunc = func() {
			if logflag {
				appslog.PlgsAppLogLoad("applog", logfile, loglevel)
			} else {
				appslog.PlgsAppLogLoad("applog", "", loglevel)
			}
			if logflag {
				gobase.Infof("applog enable\tfile=%s\tlevel=%s", logfile, loglevel)
			}
		}

		var cmd = &cobra.Command{
			Use: "applog [--file=app.log]",
			Run: func(cmd *cobra.Command, args []string) {
				// os.Setenv 只对当前进程生效
				//err := os.Setenv("applog_filename", logfile)
				//if err != nil {
				//	gobase.Warnf("set env [applog_filename] err %s", err.Error())
				//} else {
				//	os.Setenv("applog_enable", gobase.Bool2Str(logflag))
				//	os.Setenv("applog_level", loglevel)
				//}
				applogfunc()
			},
		}
		cmd.Flags().StringVarP(&logfile, "file", "f", logfile, "")
		cmd.Flags().StringVarP(&loglevel, "level", "l", loglevel, "")
		cmd.Flags().BoolVarP(&logflag, "enable", "b", logflag, "")
		applogfunc()

		return cmd, nil
	}})

}
